var _locationX;
var _locationY;
var _orientX;
var _orientY;
var _units;
var _width;
var _height;
var _imageURL;
var _imageHeight;
var _imageWidth;
var _siteId;
var _siteName;
var _buildingId;
var _buildingName;
var _buildingAddress;
var _campusId;
var _campusName;

//this is the entry point
function locateByMac(form){
	
	//first, make sure that we haven't got any leftover stuff
	//laying around from a previous run
	clearDivs();

	//now get the location xml for the requested mac
	var mac = form.mac.value;
	if(isValidMAC(mac)){
		var url = "/visualrf/location.xml?mac="+mac;
		getXml(url, locationXmlOk, locationXmlErr);
		//note: all the xml error callbacks are placed at
		//the end of this file for readability
	}
	else{
		alert("Invalid MAC address, try again");
	}
}


/**
  The XML recieved will look something like this:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
	<visualrf:location 
			version="1" 
			xmlns:visualrf="http://www.airwave.com" 
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		<device 
			mac='00:11:22:33:44:55'
			name='myclient' 
			site_id='7283514e-9470-4273-9495-a16618fea1d2' 
			site_name='my floorplan'>
				<site-width>304.11</site-width>
				<site-height>217.95</site-height>
				<x>31.50</x>
				<y>73.50</y>
		</device>
	</visualrf:location>
**/	
function locationXmlOk(xhr){
	
	var xml = xhr.responseXML;
	//get the first <device> element
	var device = xml.getElementsByTagName("device")[0];

	//assign the values we now know about
	_siteId = device.getAttribute("site_id");
	_siteName = device.getAttribute("site_name");
	_locationX = parseFloat(device.getElementsByTagName("x")[0].textContent);
	_locationY = parseFloat(device.getElementsByTagName("y")[0].textContent);

	//now, we need the site image and some other site information,
	//so it's time to get the site.xml
	//the 'images=1' parameter tells the server to include image information
	var url = "/visualrf/site.xml?images=1&site_id="+_siteId;
	getXml(url, siteXmlOk, siteXmlErr);
}



/**
site.xml will look something like this:
<visualrf:sites 
	version="1" 
	xmlns:visualrf="http://www.airwave.com" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	
	<site 
		building_id="2479040a-08c5-49f4-951c-69fa7e3a94d5" 
		desired-data-rate="36.0" 
		editable="true" 
		env="2.0" 
		floor="22.0" 
		floor_atten_db="10.0" 
		floor_height_ft="10.0" 
		gridsize="7.0" 
		height="217.95" 
		id="7283514e-9470-4273-9495-a16618fea1d2" 
		name="my floorplan" 
		orientation-x="0.0" 
		orientation-y="0.0" 
		planned-client-xmit-mw="30" 
		units="ft" 
		width="304.11">
		
		<summary 
			ap-count="9" 
			calc-time="0.02" 
			client-count="19" 
			last-calc="2009-08-31T00:12:42-06:00" 
			next-calc="2009-08-31T00:14:42-06:00" 
			radio-count="18" 
			rfid-count="0" 
			rogue-count="48"/>
			
		<image type="background">
			<filename>/var/airwave/data/7283514e-9470-4273-9495-a16618fea1d2/background.jpg</filename>
			<relative-url>visualrf/data/7283514e-9470-4273-9495-a16618fea1d2/background.jpg</relative-url>
			<pixel-width>2048</pixel-width>
			<pixel-height>1467</pixel-height>
			<file-size>114129</file-size>
		</image>
		<image type="thumbnail">
			<filename>/var/airwave/data/7283514e-9470-4273-9495-a16618fea1d2/thumbnail.jpg</filename>
			<relative-url>visualrf/data/7283514e-9470-4273-9495-a16618fea1d2/thumbnail.jpg</relative-url>
			<pixel-width>204</pixel-width>
			<pixel-height>147</pixel-height>
			<file-size>1141</file-size>
			<!-- etc -->
		</image>
		<!-- depending on how the site was created, there may be 2 or 3 different <image> elements, we just want the type="thumbnail" element in this example. -->
	</site>
</visualrf:sites>
**/
function siteXmlOk(xhr){
	var xml = xhr.responseXML;
	var site = xml.getElementsByTagName("site")[0];
	
	//gather some more site information we'll need to draw the location diagram
	_buildingId = site.getAttribute("building_id");

	//the offset is the origin of the site coordinate system
	//measured in units (feet, meters), not pixels
	_orientX = site.getAttribute("orientation-x");
	_orientY = site.getAttribute("orientation-y");
	_units = site.getAttribute("units");

	//width and height of the site, in units
	_width = site.getAttribute("width");
	_height = site.getAttribute("height");

	//now we need the image url for the floorplans background
	var imgElements = site.getElementsByTagName("image");
	for(var i = 0 ; i < imgElements.length ; ++i){
		var imgNode = imgElements[i];

		//we use the thumbnail image here because full-size images
		//can be quite large
		if(imgNode.getAttribute("type") == "thumbnail"){
			//there will only be one 'relative-url' element
			var relUrl = imgNode.getElementsByTagName("relative-url")[0];
			var heightNode = imgNode.getElementsByTagName("pixel-height")[0];
			_imageHeight = parseInt(heightNode.textContent);
			var widthNode = imgNode.getElementsByTagName("pixel-width")[0];
			_imageWidth = parseInt(widthNode.textContent);
			//prefix the url with a '/' so we don't have to worry about
			//where this page resides.
			_imageURL = "/"+relUrl.textContent;

			break;
		}
	}


	//ok, we've got everything now except the *name* of the campus and building
	//that this floorplan is on.  So the last url we hit is campus.xml,
	//being sure to include the buildings and floors in the results
	var url = "/visualrf/campus.xml?buildings=1&sites=1";
	getXml(url, campusXmlOk, campusXmlErr);

	//note that ids do not change.  If you're willing to create your sites
	//and then set up an id<->name map in the javascript or somewhere else
	//then you can bypass this last, possibly expensive, step.
	
}

function campusXmlOk(xhr){
	var xml = xhr.responseXML;
	var sites = xml.getElementsByTagName("site");

	//dig through all the sites looking for the id of the one we're interested in
	for(var i = 0 ; i < sites.length ; ++i){
		if(sites[i].getAttribute("id") == _siteId){
			//ok, this is the site, so look at the parent and grandparent
			//for building name and campus name respectively
			var bldgNode = sites[i].parentNode;
			_buildingName = bldgNode.getAttribute("name");

			//grab the address too as long as we're here
			var addressNode = bldgNode.getElementsByTagName("address")[0];
			_buildingAddress = addressNode.textContent;
			var campusNode = bldgNode.parentNode;
			_campusName = campusNode.getAttribute("name");
		}
	}

	//ok, we've got all we need, now to display it!
	showLocation();
}

function showLocation(){
	//we'll show a summary of all the sundry info we know about in a table
	//on the left
	
	var tableDiv = document.getElementById("tableGoesHere");
	var imageDiv = document.getElementById("imagesGoHere");
	var stuff = [
								["Campus", _campusName],
								["Building", _buildingName],
								["Address", _buildingAddress],
								["Site", _siteName]
							]
	var table = createAndFillTable(stuff);
	tableDiv.appendChild(table);


	var img = document.createElement('img');
	img.src = _imageURL;
	img.alt = _siteName;
	imageDiv.appendChild(img);

	//the location is in site units, so we need to calculate
	//how many pixels are in a site unit
	var pixelsPerUnit = _imageHeight / _height;
	var x = _locationX * pixelsPerUnit;
	var y = _locationY * pixelsPerUnit;

	//now we place the image of the client where it's located
	var cimg = document.createElement('img');
	cimg.src = "laptop16x16.gif";
	cimg.alt = "client";	


	//we want the position relative to the top-left of the thumbnail image
	//using relative positioning would have it relative to where it would
	//have been, so we subract off the image width and height from that.
	x -= _imageWidth;
	y -= _imageHeight;

	cimg.setAttribute("style", "position:relative; left:"+x+"px; top:"+y+"px");
	imageDiv.appendChild(cimg);


}



function clearDivs(){
	//just remove all children
	var t = document.getElementById("tableGoesHere");
	if (t.hasChildNodes()){
		while (t.childNodes.length >= 1){
  		t.removeChild(t.firstChild);       
		} 
	}

	var i = document.getElementById("imagesGoHere");
	if (i.hasChildNodes()){
		while (i.childNodes.length >= 1){
  		i.removeChild(i.firstChild);       
		} 
	}
}	

//------------------------------------
//table convenience functions --------

function createAndFillTable(data){
	var t = document.createElement('table');
	var body = document.createElement('tbody');
	t.appendChild(body);
	setStyle(t);
	fillTable(t, data);
	return t;
}

function setStyle(table){
	table.style.border = "1px solid black";
	table.style["font-family"] = "tahoma";
	table.style["font-size"] = "10pt";
	table.style.display = "";
}

function fillTable(table, vals){	
	for(var i = 0 ; i < vals.length ; ++i){
		addRow(table, vals[i]);
	}
}

function addRow(table, data){
	var tBody = table.getElementsByTagName('tbody')[0];
	var row = document.createElement('tr');
	tBody.appendChild(row);
	
	//var row = table.insertRow(numRows);
	for(var i = 0 ; i < data.length ; ++i){
		var c = row.insertCell(i);
		c.innerHTML = data[i];
	}
}
//------------------------------------


//------------------------------------
//Error handlers, these should probably 
//do something useful

function locationXmlErr(xhr){
	alert("An error occurred fetching location.xml!\n"+xhr.responseText);
}

function siteXmlErr(xhr){
	alert("An error occurred fetching site.xml!\n"+xhr.responseText);
}

function campusXmlErr(xhr){
	alert("An error occurred fetching campus.xml!\n"+xhr.responseText);
}
